﻿// Copyright (c) ZhangPeihang. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using LaserMark.Components.Authentication;
using LaserMark.Components.Events;
using LaserMark.Components.Services;
using LaserMark.Components.Utils;
using LaserMark.Control.Service;
using LaserMark.DataAccess;
using LaserMark.DataAccess.Service;
using LaserMark.Print.Service;
using LaserMark.Service;
using LaserMark.SuperDog;
using LaserMark.ViewModels;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using LaserMark.View.Services;
using System.Windows;
using AppContext = LaserMark.Service.AppContext;

namespace LaserMark
{
    /// <summary>
    ///
    /// </summary>
    public partial class App : Application
    {
        private IHost CreateHost() => Host.CreateDefaultBuilder()
            .ConfigureServices(s =>
            {
                s.AddWpfBlazorWebView();
                s.AddBootstrapBlazor(localizationConfigure: local =>
                {
                    local.IgnoreLocalizerMissing = true;
                });
                s.AddLogging(b => b.AddFileLogger());
                s.AddSingleton<IAppContext, AppContext>();
                s.AddSingleton<IRibbonTabEventBus, RibbonTabEventBus>();
                s.AddSingleton<IControl, GTControl>();
                s.AddSingleton<IPrint, JJZPrint>();
                s.AddScoped<IDBManager, DBManager>();
                s.AddAuthorizationCore();
                s.AddSingleton<AuthenticationStateProvider, AppAuthenticationProvider>();
                s.AddSingleton<ExternalAuthService>();
                s.AddScoped<InitViewModel>();
                s.AddScoped<IMachineService, MachineService>();
                s.AddScoped<IDeviceArgsService, DeviceArgsService>();
                s.AddScoped<IPhotoelectricityService, PhotoelectricityService>();
                s.AddScoped<IMarkArgsService, MarkArgsService>();
                s.AddScoped<IGCodeOrderService, GCodeOrderService>();
                s.AddScoped<ICodeTemplateService, CodeTemplateService>();
                s.AddSingleton<IGlobalStatus, GlobalStatus>();
                s.AddSingleton<IComprehensiveService, ComprehensiveService>();
                s.AddSingleton<IDogService, DogService>();
                s.AddModBus(async s =>
                {
                    var service = s.Provider!.GetRequiredService<IMarkArgsService>();
                    var mark = await service.GetMarks();
                    s.Address = mark.AltimetryAddress;
                    s.Port = mark.AltimetryPort;
                });
                s.AddScoped<ISecretService, SecretService>();
                s.AddScoped<IAuditService, AuditService>();
                s.AddScoped<IConnectLineService, ConnectLineService>();
                s.AddHttpClient<ErpHttpClient>();
                s.AddOptions<MarkOption>();
#if DEBUG
                s.AddBlazorWebViewDeveloperTools();
#endif
            }).Build();

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            var provider = CreateHost().Services;
            Resources.Add("services", provider);

            CreateHost().Start();
        }

        protected override async void OnExit(ExitEventArgs e)
        {
            base.OnExit(e);
            var service = (IServiceProvider)App.Current.FindResource("services");
            var c = service.GetRequiredService<IControl>();
            await c.AxisOff(0, 2);
            await c.AxisOff(0, 3);
            await c.AxisOff(0, 4);
            await c.SetDoBit(0, mc.MC_GPO, 1, 1);
            await c.Rest(0);
            await c.CloseControl(0);
            var g = service.GetRequiredService<IGlobalStatus>();
            var p = service.GetRequiredService<IPrint>();
            await p.Dispose();
            var l = service.GetRequiredService<IAuditService>();
            foreach (var item in g.AuditLog)
            {
                l.Log(item);
            }
            await CreateHost().StopAsync();
            if (g.IsRestart)
            {
                System.Windows.Forms.Application.Restart();
            }

        }
    }
}
